《Android 基础(二十五)》Frame Animation

简介

Frame Animation, 逐帧动画,通过定义一系列的Drawable对象来实现动画效果,可以用来作为视图的背景。
Frame Animation在代码中体现为AnimationDrawable对象,可以通过xml文件快创建,放在在/res/drawable/目录下,设置为视图背景后,调用start()方法即可执行逐帧动画。

XML文件

Tags:
< animation-list > 作为父节点,代表Animation Drawable
< item >作为子节点,代表逐帧动画内容,一张一张图片

Attributes:

属性 含义
android:oneshot=”false true”
android:variablePadding=”false true”
android:visible=”false true”
android:drawable=”@drawable/xxxxx” item图片资源
android:duration=“xxxxx” drawable播放时间,单位ms

Res:
/res/drawable/{folder}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/selected"
android:oneshot="true"
android:variablePadding="false"
android:visible="true">

<item android:drawable="@drawable/ic_action_add" android:duration="500"/>
<item android:drawable="@drawable/ic_action_anchor" android:duration="500"/>
<item android:drawable="@drawable/ic_action_alarm" android:duration="500"/>
<item android:drawable="@drawable/ic_action_amazon" android:duration="500"/>
<item android:drawable="@drawable/ic_action_ac" android:duration="500"/>

</animation-list>

Coding

使用XML资源

1
2
3
4
5
imageView.setBackgroundResource(R.drawable.frame_anim);//设置背景
Drawable bgDrawable = imageView.getBackground();//获取背景
if(bgDrawable instanceof AnimationDrawable) {
((AnimationDrawable) bgDrawable).start();//如果为AnimationDrawable则执行动画
}

纯代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
……
imageView.setBackground(createAnimationDrawable());//设置背景
Drawable bg = imageView.getBackground();
if(bg instanceof AnimationDrawable) {
((AnimationDrawable) bg).start();//开始动画
}

……
private AnimationDrawable createAnimationDrawable() {

AnimationDrawable animationDrawable = new AnimationDrawable();
animationDrawable.addFrame(getResources().getDrawable(R.drawable.ic_action_add), 500);
animationDrawable.addFrame(getResources().getDrawable(R.drawable.ic_action_anchor), 500);
animationDrawable.addFrame(getResources().getDrawable(R.drawable.ic_action_alarm), 500);
animationDrawable.addFrame(getResources().getDrawable(R.drawable.ic_action_amazon), 500);
animationDrawable.addFrame(getResources().getDrawable(R.drawable.ic_action_ac), 500);
animationDrawable.setOneShot(false);
animationDrawable.setVisible(true,true);
return animationDrawable;
}

效果图

这里写图片描述

# 动画
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×